package com.fsd.admin.service.impl;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baidu.aip.nlp.AipNlp;
import com.fsd.admin.model.I_knowledgeinfo;
import com.fsd.admin.service.I_knowledgeinfoService;
import org.apache.log4j.Logger;
import com.fsd.admin.entity.E_autoreplyEntity;
import com.fsd.admin.model.E_Autoreplylist;
import com.fsd.admin.model.E_wechat;
import com.fsd.admin.service.E_AutoreplyService;
import com.fsd.admin.service.E_userinfoService;
import com.fsd.core.util.Config;
import com.fsd.core.util.SpringContextHolder;
import com.fsd.core.wechat.entity.autoReply.MessageResponse;
import com.fsd.core.wechat.entity.message.resp.Article;
import com.fsd.core.wechat.main.CoreService;
import com.fsd.core.wechat.robot.TulingApiProcess;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 微信请求处理类
 */
public class E_wechatCoreService extends CoreService<E_wechat>{
	
	private static final Logger log = Logger.getLogger(E_wechatCoreService.class);

	//扫二维码参数类型
	/**
     * 扫码关注
     */
	public static final String scanQRcodeBind = "memberwechatbind_";

	private AipNlp BaiduClient = null;
	
    
	//微信用户ID
    private final String codeUserID = "{WeChatUserID}";
    //图灵机器人
    private final String codeTuLing = "{TuLingRobot}";

	public static final String OWNTTHINK_APIID = "c0a13083b78d2ec20546195599308638";
    
    //测试接口
    public String testMessage(E_wechat wechat, String fromUserName, String toUserName, String content) throws Exception{
    	E_AutoreplyService autoreplyService = (E_AutoreplyService) SpringContextHolder.getBean("e_autoreplyServiceImpl");
		E_autoreplyEntity reply = autoreplyService.getReplyTextMessage(wechat.getId(), content);
		return this.processMessage(wechat, fromUserName, toUserName, content, reply);
    }
    
    private String processMessage(E_wechat wechat, String fromUserName, String toUserName, 
    		String content, E_autoreplyEntity reply) throws Exception{
    	return this.processMessage(wechat, fromUserName, toUserName, content, reply, null);
    }
    /**
     * 消息处理
     * @param wechat 公众号
     * @param fromUserName openid
     * @param toUserName
     * @param content 请求消息内容
     * @param reply 回复对象
     * @param message 补充回复消息
     * @return
     * @throws Exception
     */
    private String processMessage(E_wechat wechat, String fromUserName, String toUserName, String content, E_autoreplyEntity reply, String message) throws Exception{
		I_knowledgeinfoService knowledgeinfoService = (I_knowledgeinfoService) SpringContextHolder.getBean("front_i_knowledgeinfoServiceImpl");
    	List<I_knowledgeinfo> list = knowledgeinfoService.getAllList();
		List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
		for (I_knowledgeinfo i_knowledgeinfo : list) {
			String key = i_knowledgeinfo.getAbstracts();
			String[] keys = key.split(",");
			// 获取两个文本的相似度
			JSONObject response = getBaiduClient().simnet(content, key, null);
			String json = response.toString();
			if(json.indexOf("error_msg") == -1){
				double score = response.getDouble("score");
				if(score > 0.6){
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("id" , i_knowledgeinfo.getId());
					map.put("type" , 0);
					map.put("title" , i_knowledgeinfo.getTitle());
					map.put("url" , i_knowledgeinfo.getContent());
					map.put("score" , score);
					map.put("keyword" , key);
					dataList.add(map);
				}
			}
		}
		if(dataList.size() == 0){
			//闲聊机器人
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("type" , 1);

			String rebootResult = ownthinkReboot(message);
			JSONObject json = new JSONObject(rebootResult);
			if("success".equals(json.getString("message"))){
				JSONObject dataJson = json.getJSONObject("data");
				JSONObject infoJson = dataJson.getJSONObject("info");
				map.put("title" , infoJson.getString("text"));
			}else{
				map.put("title" , "大脑短路了哦");
			}
			dataList.add(map);
		}
		StringBuffer sb = new StringBuffer();

		if(dataList != null && dataList.size() > 0 && dataList.get(0).get("url") != null){
			sb.append("找到与"+ content +"相关的内容"+ dataList.size() +"条：\n");
		}

		for (int i = 0; i < dataList.size(); i++) {
			Map<String, Object> map = dataList.get(i);
			if(map.get("url") != null){
				sb.append(i+1 + ":<a href=\"http://lumingbao.51vip.biz/aicontent-"+ map.get("id") +".htm\">"+ map.get("title") +"</a>");
			}else{
				sb.append(map.get("title").toString());
			}
		}
		String txt = sb.toString();
		return MessageResponse.getTextMessage(fromUserName, toUserName, txt);
    }

	public static final String APP_ID = "10029313";
	public static final String API_KEY = "WZP6HF2OCIMQY30ITgTtVGlr";
	public static final String SECRET_KEY = "dvCSN4FFDW2x8je2VIoPNfID9C2D7GA9";
	public static final String TULING_APIKEY = "8ecf288b2096578e0edfc4ec4d41072a";

	/**
	 * 获得百度客户端
	 * @return
	 */
	public AipNlp getBaiduClient(){
		if(BaiduClient == null){
			BaiduClient = new AipNlp(APP_ID, API_KEY, SECRET_KEY);
			// 可选：设置网络连接参数
			BaiduClient.setConnectionTimeoutInMillis(2000);
			BaiduClient.setSocketTimeoutInMillis(60000);
		}
		return BaiduClient;
	}

	/**
	 * 思知机器人
	 * @param keyword
	 * @return
	 */
	public static String ownthinkReboot(String keyword) {
		String message = "";
		try {
			keyword = URLEncoder.encode(keyword, "utf-8");
			String getURL = "https://api.ownthink.com/bot?appid=" + OWNTTHINK_APIID + "&spoken=" + keyword;
			URL getUrl = new URL(getURL);
			HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
			connection.connect();
			// 取得输入流，并使用Reader读取
			BufferedReader reader = new BufferedReader(new InputStreamReader( connection.getInputStream(), "utf-8"));
			StringBuffer sb = new StringBuffer();
			String line = "";
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			reader.close();
			// 断开连接
			connection.disconnect();
			message = sb.toString();
		}catch (Exception e){
			e.printStackTrace();
		}
		return message;
	}

	/**
	 * 处理文本消息请求
	 * @throws Exception 
	 */
	@Override
	public String textHandle(E_wechat wechat, String fromUserName, String toUserName, String content) throws Exception {
		E_AutoreplyService autoreplyService = (E_AutoreplyService) SpringContextHolder.getBean("e_autoreplyServiceImpl");
		if (autoreplyService == null){
			log.error("自动回复Service为空");
		}
		if (wechat == null){
			log.error("微信对象为空");
		}
		E_autoreplyEntity reply = autoreplyService.getReplyTextMessage(wechat.getId(), content);
		return this.processMessage(wechat, fromUserName, toUserName, content, reply);
	}
	/**
	 * 处理图片消息请求
	 */
	@Override
	public String imageHandle(E_wechat wechat, String fromUserName, String toUserName,
			String content) throws Exception {

		return this.processMessage(wechat, fromUserName, toUserName, content, null);
	}
	/**
	 * 处理链接消息请求
	 */
	@Override
	public String linkHandle(E_wechat wechat, String fromUserName, String toUserName,
			String content) throws Exception {

		return this.processMessage(wechat, fromUserName, toUserName, content, null);
	}
	/**
	 * 处理地理位置消息请求
	 */
	@Override
	public String locationHandle(E_wechat wechat, String fromUserName, String toUserName,
			String content) throws Exception {

		return this.processMessage(wechat, fromUserName, toUserName, content, null);
	}
	/**
	 * 处理音频消息请求
	 */
	@Override
	public String voiceHandle(E_wechat wechat, String fromUserName, String toUserName,
			String content) throws Exception {

		return this.processMessage(wechat, fromUserName, toUserName, content, null);
	}
	/**
	 * 处理订阅请求
	 */
	@Override
	public String subscribeHandle(E_wechat wechat, String fromUserName, String toUserName) throws Exception {
		E_userinfoService userinfoService = (E_userinfoService) SpringContextHolder.getBean("e_userinfoServiceImpl");
		userinfoService.saveObject(wechat, fromUserName);
		E_AutoreplyService autoreplyService = (E_AutoreplyService) SpringContextHolder.getBean("e_autoreplyServiceImpl");
		E_autoreplyEntity reply = autoreplyService.getReplySystemMessage(wechat.getId(), Config.WECHATMEGSUBSCRIBE);
		return this.processMessage(wechat, fromUserName, toUserName, "", reply);
	}
	/**
	 * 处理取消订阅请求
	 */
	@Override
	public String unsubscribeHandle(E_wechat wechat, String fromUserName, String toUserName) throws Exception {
		return MessageResponse.getTextMessage(fromUserName , toUserName , fromUserName+"取消订阅了");
	}
	/**
	 * 处理自定义菜单点击事件请求
	 */
	@Override
	public String clickHandle(E_wechat wechat, String fromUserName, String toUserName,String eventKey) throws Exception {
		E_AutoreplyService autoreplyService = (E_AutoreplyService) SpringContextHolder.getBean("e_autoreplyServiceImpl");
		E_autoreplyEntity reply = autoreplyService.getReplyClickMessage(wechat.getId(), eventKey);
		return this.processMessage(wechat, fromUserName, toUserName, eventKey, reply);
	}
	/**
	 * 处理扫码请求
	 */
	@Override
	public String scanHandle(E_wechat wechat, String fromUserName, String toUserName, String scene_str) throws Exception {
		String message = "";
		if(scene_str.indexOf(scanQRcodeBind) == 0){
			//微信用户信息业务
			E_userinfoService userinfoService = (E_userinfoService) SpringContextHolder.getBean("e_userinfoServiceImpl");
			message = userinfoService.saveUserInfoBindByQRcode(wechat, fromUserName, scene_str.replaceAll(scanQRcodeBind, ""));
			return MessageResponse.getTextMessage(fromUserName, toUserName, message);
		}else{
			message = "对不起！扫描二维码服务器未能找到对应处理功能！";
		}		
		return MessageResponse.getTextMessage(fromUserName , toUserName , message.toString());
	}
}
